package com.sdp.th.utils;

import java.math.BigInteger;

public class HexStringUtils {

    private static final char[] DIGITS_HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    protected static char[] encodeHex(byte[] data) {
        int l = data.length;
        char[] out = new char[l << 1];
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS_HEX[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_HEX[0x0F & data[i]];
        }
        return out;
    }

    protected static byte[] decodeHex(char[] data) {
        int len = data.length;
        if ((len & 0x01) != 0) {
            throw new RuntimeException("字符个数应该为偶数");
        }
        byte[] out = new byte[len >> 1];
        for (int i = 0, j = 0; j < len; i++) {
            int f = toDigit(data[j], j) << 4;
            j++;
            f |= toDigit(data[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }
        return out;
    }

    protected static int toDigit(char ch, int index) {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index);
        }
        return digit;
    }

    /**
     * 字节数组转16进制字符串
     * @param bs
     * @return
     */
    public static String toHexString(byte[] bs) {
        return new String(encodeHex(bs));
    }

    public static byte[] toBytes(String bs) {
        return decodeHex(bs.toCharArray());
    }
    
    /**
     * 16进制转10进制
     * @param hexString
     * @return
     */
    public static String hexToDecimal(String hexString) {
		BigInteger decimalValue = new BigInteger(hexString, 16); // 将16进制字符串转换为BigInteger对象
		return decimalValue.toString(); // 直接获取BigInteger对象的字符串表示（即10进制字符串）
	}
   
    
    /**
     * 将16进制字符串转换为2进制字符串
     * @param hex
     * @param byteSize 字节数
     * @return
     */
    public static String hexToBinary(String hex, int byteSize) {
        // 将16进制字符串转换为2进制字符串
        StringBuilder binaryString = new StringBuilder();
        for (int i = 0; i < hex.length(); i++) {
            // 处理每个16进制字符
            char hexChar = hex.charAt(i);
            String binary = Integer.toBinaryString(Integer.parseInt(String.valueOf(hexChar), 16));

            // 补足2进制数，保证每个16进制字符对应的2进制数位数是4
            while (binary.length() < 4) {
                binary = "0" + binary;
            }
            binaryString.append(binary);
        }

        // 确保2进制字符串的长度符合要求的字节数
        int requiredLength = byteSize * 8; // 字节数转化为位数
        if (binaryString.length() < requiredLength) {
            // 如果转换后位数不足，左侧补零
            while (binaryString.length() < requiredLength) {
                binaryString.insert(0, "0");
            }
        } else if (binaryString.length() > requiredLength) {
            // 如果转换后位数超过，截取为所需长度
            binaryString.setLength(requiredLength);
        }

        return binaryString.toString();
    }
    
    
    /**
     * 从二进制字符串中，获取制定位的值
     * @param binaryString
     * @param bitPosition
     * @return
     */
    public static int getBitValue(String binaryString, int bitPosition) {

        // 计算该位置对应的字符索引
        int length = binaryString.length();
        
        // 获取对应位置的字符（'0' 或 '1'）
        char bitChar = binaryString.charAt(length - 1 - bitPosition);
        
        // 将字符转换为整数并返回
        return bitChar == '1' ? 1 : 0;
    }
    
    /**
     * 16进制转ASCII
     * @param hexStr
     * @return
     */
    public static String hexToAscii(String hexStr) {
		StringBuilder output = new StringBuilder("");
		for (int i = 0; i < hexStr.length(); i += 2) {
			// 每两个字符分为一组
			String str = hexStr.substring(i, i + 2);
			// 将每组的16进制数转换为对应的ASCII字符
			char asciiChar = (char) Integer.parseInt(str, 16);
			// 添加到结果字符串中
			output.append(asciiChar);
		}
		return output.toString();
	}
}